/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <iostream>
#include <cstdlib>
#include <fstream>
#include "dal_dmabufheap/DmaBufHeapTopicSelector.hpp"
#include <nlohmann/json.hpp>

using json = nlohmann::json;

namespace dal_dmabufheap {

DmaBufHeapTopicSelector* DmaBufHeapTopicSelector::singleton_ = nullptr;

DmaBufHeapTopicSelector::DmaBufHeapTopicSelector()
{
    const char* env_value = std::getenv("DAL_TOPIC_TYPE_CONF");
    if (!env_value)
        return;
    
    std::ifstream file(env_value);
    if (!file.is_open()) {
        std::cerr << "Error: Failed to open JSON file: " << env_value << std::endl;
    }

    json json_data;
    try {
        file >> json_data;
    } catch (const std::exception& e) {
        std::cerr << "Error: Failed to parse JSON file: " << e.what() << std::endl;
        return;
    }

    try {
        json topics = json_data.value("Topics", json::object());

        for (const auto& pair : topics.items()) {
            const std::string& key = pair.key();
            const json& value = pair.value();

            // 将字符串放入相应的集合中
            if (key == "DmabufHeap" && value.is_array()) {
                for (const std::string& topic : value) {
                    dbh_topics_.insert(topic);
                }
            } else if (key == "Mixed" && value.is_array()) {
                for (const std::string& topic : value) {
                    mixed_topics_.insert(topic);
                }
            }
        }
    } catch (const std::exception& e) {
        dbh_topics_.clear();
        mixed_topics_.clear();
        std::cerr << "Error: Failed to parse JSON data: " << e.what() << std::endl;
    }
}

DmaBufHeapTopicSelector* DmaBufHeapTopicSelector::GetInstance()
{
    if (singleton_ == nullptr) {
        singleton_ = new DmaBufHeapTopicSelector();
    }
    return singleton_;
}


bool DmaBufHeapTopicSelector::IsDbhTopic(const std::string& topic)
{
    return dbh_topics_.find(topic) != dbh_topics_.end();
}

bool DmaBufHeapTopicSelector::IsMixedTopic(const std::string& topic)
{
    return mixed_topics_.find(topic) != mixed_topics_.end();
}

} // namespace dal_dmabufheap